#!/usr/bin/env perl
#
# Nagios Appliance welcome web
#
# Author: Jordi "Txor" Casas Ríos <txorlings@gmail.com>
#

use Mojolicious::Lite;

get '/' => sub {
	my $self = shift;
	my $ip = $self->agent_ip;
	if ($ip eq "127.0.0.1") {
		# Supose local access, show them all options
		my $cgi = $self->param('cgi');
		if (defined $cgi) {
			if ($cgi eq 'nagios') {
				# Redirect to Nagios.
				$self->redirect_to('http://127.0.0.1:8080/nagios/');
			}
			elsif ($cgi eq 'nconf') {
				# Redirect to NConf.
				$self->redirect_to('http://127.0.0.1:8080/nconf/');
			}
			elsif ($cgi eq 'terminal') {
				# Raise root terminal code.
				system("DISPLAY=:0 xterm -e 'sudo bash' &");
			}
			elsif ($cgi eq 'yast') {
				# Raise YaST code.
				system("DISPLAY=:0 xterm -e 'sudo /sbin/YaST2' &");
			}
		}
		$self->render('local');
	}
	else {
		# Supose remote access, show only monitoring tools and SSH explanation.
		my $cgi = $self->param('cgi');
		my $host = $self->request_ip;
		if (defined $cgi) {
			if ($cgi eq 'nagios') {
				# Redirect to Nagios.
				$self->redirect_to("http://$host:8080/nagios/");
			}
			elsif ($cgi eq 'nconf') {
				# Redirect to NConf.
				$self->redirect_to("http://$host:8080/nconf/");
			}
		}
		$self->render('remote');
	}
};

# helper to get the requested host IP and tamper with it...
helper request_ip => sub {
	my $self  = shift;
	my $host = $self->req->url->base->host;
	return "$host";
};

# helper to get the agent IP
helper agent_ip => sub {
	my $self  = shift;
	my $ip    = $self->tx->remote_address;
	return "$ip";
};

app->secret('Ih1O9p9a');
app->start;

